#!/usr/bin/env python
# encoding: utf-8

# Copyright (c) 2009 Klaas Pieter Annema, Glen Hunt
# 
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

from datetime import date, datetime

class RTMTask(object):
	
	def __init__(self, vTodo):
		self.uuid = None
		self.completed = False
		self.tags = []
		self.due = None
		self.priority = 0
		self.summary = ''
	
		self.parse(vTodo)
		
	def __str__(self):
		
		priorityText = str(self.priority)
		if (self.priority is 0):
			priorityText = ''
		
		dueText = 'N/A'
		if self.due != None:
			duetime = self.due.strftime('%H:%M')
			
			if duetime != '00:00':
				dueText = '%-5s' % duetime
				
		return '%s	%s	%s' % (priorityText, dueText, self.summary)
		
		
	def parse(self, vTodo):		
		# UUID		
		if vTodo.has_key('uid'):
			self.uuid = vTodo['uid']
		else:
			raise AssertionError('Every todo must have a uuid')
		
		# COMPLETED		
		if vTodo.has_key('status'):
			if vTodo['status'] == 'COMPLETED':
				self.completed = True
			else:
				self.completed = False
		
		# DUE	
		if vTodo.has_key('due'):
			duedate=str(vTodo['due']).replace('T','')
			if len(duedate) > 10:
				self.due = datetime.strptime(duedate, "%Y%m%d%H%M%S")
			else:
				self.due = datetime.strptime(duedate, '%Y%m%d')
		
		# TAGS
		if vTodo.has_key('description'):					
					
			description = vTodo['description']		
			tags = description.splitlines()[0].split(':').pop().split(',');
					
			for tag in tags:
				self.tags.append(tag.strip())
				
		# PRIORITY
		if vTodo.has_key('priority'):
			priority = vTodo['priority']
			
			if priority == 1:
				self.priority = 1
			
			elif priority > 1 and priority <= 5:
				self.priority = 2
				
			elif priority > 5:
				self.priority = 3
				
		# SUMMARY
		if vTodo.has_key('summary'):			
			self.summary = vTodo['summary']
			
			
		# A compare function for sorting tasks
		def compare(taskA, taskB):			
			return cmp(taskA.priority, taskB.priority)